use strict; use warnings;
use Data::Dumper;
use LWP::Simple;
use HTML::TreeBuilder;

use XML::Writer;
my $w = XML::Writer->new( DATA_MODE => 1, DATA_INDENT=>4 );


my $user = 'metaperl';

my $kgs = 'http://www.gokgs.com';
my $url = "$kgs/gameArchives.jsp";

my $final_url="$url?user=$user";

my $html = get($final_url);


my $tree = HTML::TreeBuilder->new_from_content($html);

my $table = $tree->look_down('_tag' => 'table');

my @potential_game = $table->look_down('_tag' => 'tr');

#warn scalar @potential_game;

my @viewable_game = grep {
  my $elem = $_;

  my $game_link = $elem->look_down(href => qr!files.gokgs.com/games!);

  if ($game_link) {
    my $content = ($game_link->content_list)[0];
    $content eq 'Yes';
  } else {
    ();
  }

} @potential_game;

sub fix_colspan {
  my($td)=@_;

  my $colspan = $td->attr('colspan');
  
  if (defined($colspan) and $colspan == 2) {

    my $black_white = ($td->content_list)[0];
    my @a = $td->look_down(_tag => 'a');
    my ($black, $white) = @a[1,2];

    my @td = (HTML::Element->new_from_lol( [td => $black] ) );
    push @td, HTML::Element->new_from_lol( [td => $white] ) ;
    $td->replace_with(@td)->delete;
  }
}



my @tag = qw(viewable white black setup start_time type result);
use List::MoreUtils qw(zip natatime);

my $U = \&as_url;
my $P = \&as_player;
my $H = \&as_html;
my $C = \&as_content;
my $T = \&as_text;

my @print = ($U, $P, $P, $T, $C, $C, $C);

sub tag {
  my ($tag, $close)=@_;

  '<' . ($close ? '/' : '') . $tag . '>' ;
}

sub ptag {
  my $result = tag(@_);
  print "$result\n";
}

sub as_content {
  my($elem)=@_;

  $w->characters(($elem->content_list)[0]);
}

sub as_url {
  my($elem)=@_;

  my $a = $elem->look_down(href => qr/./);
  $w->characters($a->attr('href'));


}

sub as_player {
  my($elem)=@_;

  my $a = $elem->look_down(_tag => 'a');

  $w->dataElement(url => "$kgs/" . $a->attr('href'));
  $w->dataElement(name => ($a->content_list)[0]);

}

# reset emacs mode


sub as_html {
  my($elem)=@_;

  $w->characters($elem->as_HTML);
}

sub as_text {
  my($elem)=@_;

  $w->characters($elem->as_text);
}



$w->startTag('gamelist');

for my $game (@viewable_game) {

  my @td = $game->look_down('_tag' => 'td');
  fix_colspan($_) for @td;
  @td = $game->look_down('_tag' => 'td');

  my @zip = zip @tag, @td, @print ;
  my $it = natatime 3, @zip;

  $w->startTag('game');

  while (my ($tag, $td, $print) = $it->()) {

    $w->startTag($tag);
    $print->($td) ;
    $w->endTag();


  }
  
  $w->endTag('game');


}

$w->endTag;
 
